<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Category;
use AppBundle\Form\CategoryType;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class CategoryController extends Controller
{
    /**
     * @Route("/category/add")
     * @param Request $request
     * @Method({"GET","POST"})
     * @return Response
     */
    public function addAction(Request $request)
    {
        $category = new Category();
        $form = $this->createForm(new CategoryType(),$category);
        $form->handleRequest($request);

        if($form->isSubmitted()&&$form->isValid())
        {
            $em = $this->getDoctrine()->getManager();
            $em->persist($category);
            $em->flush();

            return new Response($category->getId());
        }

        return $this->render('default/new.html.twig', array(
            'form' => $form->createView(),
        ));
    }

    /**
     * @Route("/category/testadd")
     */
    public function testAddAction()
    {
        $category0= new Category();
        $category0->setName("食品");
        $category0->setPid(0);

        $category1 = new Category();
        $category1->setName("水果");
        $category1->setPid(1);

        $em = $this->getDoctrine()->getManager();
        $em->persist($category0);
        $em->persist($category1);

        $em->flush();

        return new Response("ok");
    }

    /**
     * @Route("/category/test")
     * @return int
     */
    public function testAction(){
        $response = $this->forward('AppBundle:User:test');

        return $response;
    }

    public function categAction(){
        return new Response('Test ok');
    }



}
